import axios from "axios";
import { CancelToken } from "axios";
import { TOKEN_KEY } from "@/enums/CacheEnum";
const BASE_URL = import.meta.env.VITE_APP_BASE_API; // 基础URL，可以根据环境变量或配置来调整
const TIMEOUT = 10000; // 默认超时时间

class HYRequest {
  constructor(options = {}) {
    // 创建axios实例
    this.instance = axios.create({
      baseURL: options.baseURL || BASE_URL,
      timeout: options.timeout || TIMEOUT,
    });
    this.pendingRequests = new Map(); // 用于保存当前挂起的请求

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        const token = localStorage.getItem(TOKEN_KEY);
        if (config.headers && token) {
          config.headers.Authorization = token; // "Bearer " +
        }

        // 请求取消处理
        const source = CancelToken.source();
        config.cancelToken = source.token;
        this.pendingRequests.set(config.url, source);

        return config;
      },
      (err) => {
        return Promise.reject(err);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => {
        // 请求成功后从挂起列表中移除
        this.pendingRequests.delete(response.config.url);
        return response;
      },
      (error) => {
        this.pendingRequests.delete(error.config.url);

        // 统一处理错误
        if (!error.response) {
          console.error("网络错误");
          return Promise.reject(new Error("Network Error"));
        }

        const status = error.response.status;
        switch (status) {
          case 401:
            console.error("未授权访问，请登录");
            break;
          case 403:
            console.error("没有权限");
            break;
          case 500:
            console.error("服务器错误");
            break;
          default:
            console.error("请求错误", status);
        }
        return Promise.reject(error);
      }
    );
  }

  // 核心请求方法，支持重试机制
  request(config, retries = 3) {
    return new Promise((resolve, reject) => {
      const attemptRequest = (retryCount) => {
        this.instance
          .request(config)
          .then((res) => {
            resolve(res.data);
          })
          .catch((err) => {
            if (retryCount > 0) {
              console.log(`请求失败，正在重试... 剩余次数：${retryCount}`);
              attemptRequest(retryCount - 1);
            } else {
              reject(err);
            }
          });
      };
      attemptRequest(retries);
    });
  }

  // 各种HTTP方法的简化调用
  get(config, retries) {
    return this.request({ ...config, method: "get" }, retries);
  }

  post(config, retries) {
    return this.request({ ...config, method: "post" }, retries);
  }

  put(config, retries) {
    return this.request({ ...config, method: "put" }, retries);
  }

  delete(config, retries) {
    return this.request({ ...config, method: "delete" }, retries);
  }

  // 取消所有请求
  cancelAllRequests() {
    this.pendingRequests.forEach((source) => {
      source.cancel("请求已取消");
    });
    this.pendingRequests.clear();
  }
}

// 默认导出实例，这样在使用时直接引入实例即可
export default new HYRequest({
  baseURL: BASE_URL,
  timeout: TIMEOUT,
});
// 命名导出
//如果想创建多个实例可以这样创建
// export const hyRequest1 = new HYReqest("http://123.207.32.32:8000")
// import HYRequestInstance, { hyRequest1 } from "路径";//在其他文件导入默认实例和命名实例的写法

// const hyRequest2 = new HYReqest("http://123.207.32.32:8000")
